package top.mollysu.sell.service;

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import top.mollysu.sell.VO.ResultVO;
import top.mollysu.sell.util.ServerEncoderUtil;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author kosmosr
 * @Date 2018/3/25
 */
@Component
@Log4j2
@ServerEndpoint(value = "/webSocket", encoders = {ServerEncoderUtil.class})
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSockets.add(this);
        log.info("【WebSocket消息】有新的消息，总数:{}", webSockets.size());
    }

    @OnClose
    public void onClose(Session session) {
        webSockets.remove(this);
        log.info("【WebSocket消息】连接断开，总数:{}", webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【WebSocket消息】收到客户端发来的消息，{}", message);
    }

    public void sendMessage(ResultVO message) {
        for (WebSocket webSocket : webSockets) {
            log.info("【WebSocket消息】广播消息, message={}", message);
            try {
                webSocket.session.getBasicRemote().sendObject(message);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (EncodeException e) {
                e.printStackTrace();
            }
        }
    }
}
